<template>
  <div v-loading="loading" class="normal-setting-box service-provider-view">
   <div class="normal-setting-box-main" v-show="!loading">
     
     <div class="service-top" v-if="!hideTopTip && !loading">
       <div>
         <span class="icon iconfont icon-tip mar-r-8"></span>
         {{$t('serviceProvider.joinWaitApproval', {num: approvalCount})}}
         <span class="cur-point c-primary mar-l-8" @click="gotoUrl('PageServiceAuditList')">{{$t('common.base.clickView')}}</span>
       </div>
       <div class="cur-point" @click="gotoHideTip"><span class="icon iconfont icon-fe-close"></span></div>
     </div>

     
     
     <div :class="['service-main','flex', {'service-hide-tip': hideTopTip}]">
      
      <base-collapse 
        class="service-provider-main-content"
        :direction.sync="collapseDirection"
      >
        <template slot="left">
          
          <div
            v-show="!isProviderUser && collapseLeft"
            class="left-menu"
          >
            <div class="provider-menu-content">
              <div class="flex mar-b-12 mar-r-12">
                <!--搜索框-->
                <el-input
                    v-model="deptKeyword"
                    prefix-icon="el-icon-search"
                    v-trim:blur
                    :placeholder="$t('common.placeholder.inputKeywordToSearch', {data1: ''})"
                    class="mar-r-8"
                    @keyup.enter.native="getAllProviderTree"></el-input>
                <!--新建服务商-->
                <el-tooltip effect="dark" :content="$t('common.pageTitle.pageServiceProviderCreate')" placement="right">
                  <el-button v-if="!isProviderUser && authAddProvider" type="plain-third" @click="gotoUrl('PageServiceProviderCreate')"><i class="iconfont icon-add"></i></el-button>
                </el-tooltip>
              </div>
              <!--按结构查看服务商树-->
              <base-tree
                  isDefaultExpand
                  :selected="selectedDept"
                  :data="deptsProviders"
                  :node-render="nodeRender"
                  @node-selected="handleNodeClick"/>
              <!--按结构查看服务商树-->
            </div>
            <div
                :class="['provider-delete-main', 'cur-point', selectedRole.id === ServiceManageEnum.provider.Id ?'department-role-selected':'']"
                @click="chooseDelProvider()">
              <span>{{$t('common.base.cancelledProvieder')}}</span>
              <i class="icon iconfont icon-right1"></i>
            </div>
          </div>
          
        </template>
        <template slot="right">
          
          <div v-loading="loadingRight" class="main">
            <component :is="cmpName" :share-data="shareData" :service-tab="serviceTab" @refresh="refresh"></component>
          </div>
          
        </template>
      </base-collapse>
        
     </div>
   </div>
  </div>
</template>

<script>
import { getRootWindow } from '@src/util/dom';
import { getRootWindowInitData } from '@src/util/window'
// api
import { getProviderTree, getApproveCount } from '@src/api/serviceProviderApi'
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()
// component
import AccountList from './accountList/AccountList.vue'
import ProviderList from "./provider/providerList/ProviderList";
import EngineerList from "./engineer/engineerList/EngineerList";
import ProviderMain from "./MainTab/ProviderMain";
import EngineerMain from "./MainTab/EngineerMain";

import ServiceManageEnum from '@model/enum/ServiceManageEnum'
import { storageGet } from "@src/util/storage";
import { openAccurateTab } from '@src/util/platform';
import {PageRoutesTypeEnum} from "@model/enum/PageRoutesEnum";
const PROVIDER_ADD_AUTH  = 'provider_add_auth' // 服务商新建权限


export default {
  name: 'service-manage',
  components: {
    AccountList,
    ProviderList,
    EngineerList,
    ProviderMain,
    EngineerMain,
  },
  computed:{
    // 是否开始服务商灰度
    isProviderManager() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.providerManager || false
    },
    // // 0：钉钉端，1：自建，2：企微端
    tenantType() {
      return getRootWindowInitData().tenantType
    },
    // 是否是服务商
    isProviderUser() {
      return getRootWindowInitData().isProviderUser || false
    },
    // 新建服务商权限
    authAddProvider() {
       return storageGet(PROVIDER_ADD_AUTH)
    },
  },
  data() {
    return {
      loading: false,
      selectedRole: {},
      deptKeyword: '',
      loadingRight: false,
      cmpName: '',
      showProvider: true,
      shareData: {
        status: '1',
        hideTopTip: false,
      },
      serviceTab: 'provider',
      hideTopTip: true,
      deptsProviders: [], // 服务商树
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      selectedDept: {}, // 按结构查询选中的
      label:'', // 修改的标签
      ServiceManageEnum,
      collapseLeft: true,
      collapseRight: false,
      approvalCount: 0,
      collapseDirection: 'left',
    }
  },
  async mounted() {
   try {
     this.loading = true;
     await this.getApproveCount();
     await this.getAllProviderTree();
   } catch (e) {
     console.error(e)
   } finally {
     this.loading = false;
   }
  },
  methods: {
    disposeFormListViewTime,
    // 获取服务商待审批数量
    async getApproveCount() {
      try {
        let res = await getApproveCount();
        if(res.success) {
          this.approvalCount = res?.result || 0
          this.hideTopTip = (localStorage.getItem('IS_CLICK_REMOVE_SERVICE_MANAGE_TIP') === 'true') || !(this.approvalCount && !this.isProviderUser); //服务商不显示这个tip
        } else {
          this.hideTopTip = true; // 查询false的时候没有权限去查看审批列表
        }
      } catch (e) {
        console.error(e)
      }
    },

    // 服务商树查询
    async getAllProviderTree() {
      try {
        this.loading = true;
        let res = await getProviderTree(this.deptKeyword ? { keyword: this.deptKeyword } : {});
        if(res.success && res.code === 0) {
          if(this.isProviderUser) {
            this.selectedRole.id = ServiceManageEnum.EngineerMain.Id;
            this.cmpName = ServiceManageEnum.EngineerMain.cmpName; // 工程师列表
            let value = res.result[0];
            this.shareData = {
              name: value?.name, // 服务商名称
              code: value?.providerCode, // 服务商编码
              tenantProviderId: value?.id, // 租户服务商id
              status: '1',
              hideTopTip: this.hideTopTip,
            };
            return;
          } else {
            this.deptsProviders = res.result;
            // 默认选中第一个
            this.selectedDept = this.deptsProviders?.[0]
            this.selectedRole.id = ServiceManageEnum.providerMain.Id;
            this.cmpName = ServiceManageEnum.providerMain.cmpName; // 服务商&工程师列表
            this.shareData = {
              status: '1',
              hideTopTip: this.hideTopTip,
            }
          }
          return;
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false;
      }
    },


    // 按部门服务商树渲染
    nodeRender(h, node) {
      if(node?.type === 1) {
        return (
            <span>{node?.name}</span>
        )
      }else {
        let countProvider = node?.children?.filter(item => item.type === 1)?.length || 0
        let content = (
            <span>
          {node?.name}（{countProvider}）
        </span>
        );
        return content;
      }
    },

    refresh() {
      this.getAllProviderTree()
    },

    //选择按部门分类的树
    handleNodeClick(val) {
      this.selectedDept = val;
      if(val.type === 0) { // 选择的是部门
        this.selectedRole.id = ServiceManageEnum.providerMain.Id;
        this.cmpName = ServiceManageEnum.providerMain.cmpName; // 服务商&工程师列表
        this.shareData = {
          status: '1', // 不是注销状态
          hideTopTip: this.hideTopTip,
        }
        if(val.parentId || val.providerRelationTagId) this.shareData.tagId = val.treeId // 最上面一级是不需要传递tagID的，默认查所有
      } else { // 选择的是服务商
        this.selectedRole.id = ServiceManageEnum.EngineerMain.Id;
        this.cmpName = ServiceManageEnum.EngineerMain.cmpName; // 工程师列表
        this.shareData = {
          name: val?.name, // 服务商名称
          code: val?.providerCode, // 服务商编码
          tenantProviderId: val?.treeId, // 租户服务商id
          status: '1',
          hideTopTip: this.hideTopTip,
        };
      }
    },

    // 选择已注销的服务商
    async chooseDelProvider() {
      this.selectedDept = {}; // 按部门结构的树清除选中状态
     // this.$refs.labelTreeRef.setCurrentKey(null)
      this.selectedRole.id = ServiceManageEnum.provider.Id;
      this.cmpName = ServiceManageEnum.provider.cmpName; // 显示已注销的服务商页面
      this.shareData = {
        status: '0', // 注销状态
        hideTopTip: this.hideTopTip,
      }
    },

    // 选择已删除账号
    chooseDelRole() {
      //this.$refs.labelTreeRef.setCurrentKey(null)
      this.selectedDept = {}; // 按部门结构的树清除选中状态
      this.selectedRole.id = ServiceManageEnum.account.Id;
      this.cmpName = ServiceManageEnum.account.cmpName; // 显示已删除的账号页面
    },

    btnCollapse(dir) {
      if (dir === 'left') {
        this.collapseLeft = !this.collapseLeft;
        this.collapseRight = true;
      } else {
        this.collapseRight = !this.collapseRight;
        this.collapseLeft = true;
      }
    },

    // 服务商新建
    gotoUrl(type) {
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum[type],
        fromId,
      })
    },

    gotoHideTip() {
      this.hideTopTip = true;
      this.shareData.hideTopTip = true;
      localStorage.setItem('IS_CLICK_REMOVE_SERVICE_MANAGE_TIP', 'true') // 服务商管理审批的tip是否显示，当待审批页面有新服务商发起审批时，点击 X 关闭提醒，当前登录状态不在提醒，如下次登录进入如有待审批则仍自动弹出提示
    },
  },
}
</script>

<style scoped lang="scss">
.normal-setting-box {
  padding: 16px 0 16px 16px;
  height: 100%;
  overflow: hidden;
  min-width: 1200px;
  &-main {
    height: 100%;
    .service-top {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #FFFBE6;
      border-radius: 4px;
      border: 1px solid #FFE58F;
      margin: 0 12px 8px 0;
      padding: 0 17px;
      font-size: 14px;
      font-weight: 400;
      color: $text-color-regular;
      .icon-tip {
        color: #FAAD14;
      }
      .icon-fe-close {
        font-size: 9px;
      }
    }
    .service-main {
      height: calc(100% - 48px);
      .left-menu {
        min-width: 230px;
        width: 100%;
        height: 100%;
        overflow: hidden;
        background: #fff;
        box-sizing: border-box;
        border-radius: 4px;
        position: sticky;
        position: -webkit-sticky;
        padding-top: 12px;
        display: flex;
        flex-direction: column;
        .provider-menu-content {
          flex-grow: 1;
          padding-left: 12px;
          height: calc(100% - 80px);
          ::v-deep .el-button--plain-third {
            padding: 8px;
            .iconfont {
              margin-right: 0;
            }
          }
          ::v-deep .el-tree-node__content {
            height: 28px;
            margin: 2px;
            &:hover {
              color: $color-primary;
              background-color: $color-primary-light-1;
            }
          }
          .base-tree {
            height: calc(100% - 44px);
            overflow: auto;
            ::v-deep .base-tree-node-content {
              margin-right: 12px;
              .base-tree-node-name {
                overflow: hidden;
                text-overflow: ellipsis;
              }
            }
          }
        }
        .provider-delete-main {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 17px 0 12px;
          height: 40px;
          background: #FAFAFA;
          box-shadow: 0px -1px 0px 0px #E8E8E8;
          &:hover, &.department-role-selected{
            background-color: $color-primary-light-1;
            color: $color-primary;
          }
          span {
            height: 20px;
            font-size: 14px;
            font-weight: 400;
            line-height: 20px;
          }
        }
      }
      .collapse {
        display: flex;
        align-items: center;
        .base-collapse-btn-left, .base-collapse-btn-right {
          height: 50px;
        }
      }
      .main {
        width: 100%;
        overflow: hidden;
      }
    }
    .service-hide-tip {
      height: 100%;
    }
    .c-primary {
      color: $color-primary;
    }
  }
}
</style>
<style lang="scss">
.service-provider-view {
  .base-collapse-left.active {
    max-width: 230px;
    min-width: 230px;
  }
  .base-collapse-right.active {
    max-width: 580px;
    min-width: 580px;
  }
  .base-collapse-right {
    min-width: 580px;
  }
  .base-collapse-left, .base-collapse-right {
    width: 100%;
  }
  .provider-main-new {
    .provider-top {
      min-width: 840px;
      overflow: hidden;
    }
    .engineer-name {
      @include text-ellipsis-2();
    }
    .table-footer {
      .list-info {
        min-width: 100px;
      }
    }
  }
}
</style>